package com.htbb.base.handler;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ModelAttribute;


import java.io.IOException;

import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
* @author wuyongde   
* @date 2016年10月26日 上午10:43:46 
* @ClassName: CrossDomainHandler 
* @Description:解决跨域问题过滤器
 */
@ControllerAdvice
public class CrossDomainHandler {
	
    private Logger log = LoggerFactory.getLogger(this.getClass());
    
    @ModelAttribute
    public void crossDomain(HttpServletRequest request,ServletResponse response) throws IOException {
    	String requestURI=((HttpServletRequest)request).getRequestURI();
		//解决初始化swagger导致电脑卡死问题
		if(requestURI.indexOf("api-docs") == -1){ 
			
			/**
			 * add by wzc
			 * 把ip放入threadlocal
			 */
			//setUserId(request);
			
			log.debug("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~解決跨域 filter----start~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
	        HttpServletResponse httpServletResponse = (HttpServletResponse) response;
	        
	        String origin = request.getParameter("Origin");
	        if(StringUtils.isBlank(origin)){
	            origin= ((HttpServletRequest)request).getHeader("Origin");
	        }
	        if(StringUtils.isBlank(origin)){
	            origin="*";
	        }
	        httpServletResponse.setHeader("Access-Control-Allow-Origin", origin);
	        
	        httpServletResponse.setHeader("Access-Control-Allow-Credentials", "true");
	        httpServletResponse.setHeader("Access-Control-Max-Age", "120");
	        httpServletResponse.setHeader("Access-Control-Allow-Headers","Origin X-Requested-With, Content-Type, Accept");
	        httpServletResponse.setHeader("Access-Control-Allow-Methods","GET, POST, PUT");
	        
		}
    }
    
    
    public String getRemoteHost(HttpServletRequest request){
	    String ip = request.getHeader("x-forwarded-for");
	    if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)){
	        ip = request.getHeader("Proxy-Client-IP");
	    }
	    if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)){
	        ip = request.getHeader("WL-Proxy-Client-IP");
	    }
	    if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)){
	        ip = request.getRemoteAddr();
	    }
	    return ip.equals("0:0:0:0:0:0:0:1")?"127.0.0.1":ip;
	}
    
}
